<template>
  <div class="headerbox">
    <div class="header">
      <div class="headerL">
        <a onclick="javascript:history.back(-1)" class="goback"
          ><img src="/assets/images/goback.png"
        /></a>
      </div>
      <div class="headerC">
        <p>详情描述</p>
      </div>
      <div class="headerR">
        <a href="javascript:void(0)"
          ><img src="/assets/images/more.png" id="share"
        /></a>
      </div>
    </div>
  </div>
  <div class="clear"></div>
  <div class="h50"></div>
  <div class="clear"></div>
  <!-- 顶部轮播图 -->
  <van-swipe class="aui-m-slider" :autoplay="3000" indicator-color="#00EEEE">
    <van-swipe-item>
      <van-image
        width="100%"
        height="380"
        fit="cover"
        :src="product.thumbs_text"
      />
    </van-swipe-item>
    <van-swipe-item>
      <van-image
        width="100%"
        height="380"
        fit="cover"
        src="/assets/images/01.jpg"
      />
    </van-swipe-item>
    <van-swipe-item>
      <van-image
        width="100%"
        height="380"
        fit="cover"
        src="/assets/images/01.jpg"
      />
    </van-swipe-item>
    <van-swipe-item>
      <van-image
        width="100%"
        height="380"
        fit="cover"
        src="/assets/images/01.jpg"
      />
    </van-swipe-item>
  </van-swipe>

  <div class="clear"></div>

  <div class="detailbox">
    <div class="price">
      单独购买：<em>￥</em>{{ product.price }} | 拼团价格：<em>￥</em
      >{{ product.team }}
    </div>
  </div>
  <div class="allkbox"></div>

  <div class="info_choice">
    <!-- Sku 商品规格 -->
    <div class="commodity" @click="SkuShow = true">
      <div class="opt">
        <div class="title wanl-gray">选择</div>
        <div class="option">
          <div class="selected">
            <div>
              <span>尺码</span>
              <span>颜色</span>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray" onclick="location.href = 'sku.html' ">
        <img src="/assets/images/go.png" />
      </div>
    </div>
    <!-- 服务 -->
    <div class="commodity" @click="TipShow = true">
      <div class="opt">
        <div class="title wanl-gray">服务</div>
        <div class="option">
          <div class="selected">
            <div>
              <span>7天无理由退款</span>
              <span>·</span>
              <span>24小时内发货</span>
              <span>·</span>
              <span>假一赔十</span>
            </div>
          </div>
        </div>
      </div>
      <div class="wanl-gray" onclick="location.href = 'server.html' ">
        <img src="/assets/images/go.png" />
      </div>
    </div>
  </div>
  <div class="clear"></div>
  <div class="allkbox"></div>
  <div class="clear"></div>

  <!-- 选项卡 -->
  <van-tabs v-model:active="TabActive" type="card" color="#EE0A24">
    <van-tab title="产品参数">
      <div v-html="product.content"></div>
    </van-tab>
    <van-tab title="商品评价">
      <div class="rate-header">
        <div class="rate-score">
          <h4>与描述相符</h4>
          <strong>4.5</strong>
        </div>
        <div class="rate-graph">
          <van-rate v-model="rate" allow-half readonly />
        </div>
      </div>
      <!-- 评论内容 -->
      <div class="rate-content">
        <div v-if="comment">
          <div class="review-box" v-for="(item, index) in comment" :key="index">
            <div class="review-item">
              <!-- 评论人 -->
              <div class="from-whom">
                <div class="avatar">
                  <img :src="item.business.avatar_text" alt="" />
                </div>
                <div class="name">
                  {{ item.business.name ? item.business.name : "暂无昵称" }}
                </div>
              </div>
              <!-- 评论内容 -->
              <div class="review-details">
                <div class="content">{{ item.comment }}</div>
                <div>
                  <img :src="item.thumbs_text" alt="" />
                </div>
                <div class="time">{{ item.comtime_text }}</div>
                <van-rate v-model="item.rate" readonly />
              </div>
            </div>
          </div>
        </div>
        <div v-else>
          <div class="rate-empty">该商品还没有人写评价呢</div>
        </div>
      </div>
    </van-tab>
  </van-tabs>
  <!-- sku -->
  <van-sku
    ref="SkuRef"
    v-model="SkuShow"
    :sku="sku"
    :properties="properties"
    :goods="goods"
    :goods-id="product.id"
    @add-cart="AddCart"
    @buy-clicked="Buy"
  >
    <!-- 自定义 sku actions -->
    <template #sku-actions="props">
      <div class="van-sku-actions">
        <van-button
          square
          size="large"
          type="warning"
          @click="props.skuEventBus.emit('sku:addCart')"
        >
          加入购物车
        </van-button>

        <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
        <van-button
          square
          size="large"
          type="danger"
          @click="props.skuEventBus.emit('sku:buy')"
        >
          单独购买
        </van-button>
        <van-button square size="large" type="danger" @click="JoinTeam"> 参与拼团 </van-button>
      </div>
    </template>
  </van-sku>

  <!-- 协议条款 -->
  <van-action-sheet v-model:show="TipShow" title="协议条款">
    <div class="content">内容</div>
  </van-action-sheet>

  <!-- 动作栏 -->
  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" color="#ee0a24" />
    <van-action-bar-icon
      icon="cart-o"
      text="购物车"
      :badge="product.cart"
      v-if="product.cart"
      @click="ToCart"
    />
    <van-action-bar-icon icon="cart-o" text="购物车" v-else @click="ToCart" />
    <van-action-bar-icon
      icon="star"
      text="已收藏"
      color="#ff5000"
      @click="collection"
      v-if="product.collected"
    />
    <van-action-bar-icon icon="star-o" text="收藏" @click="collection" v-else />
    <van-action-bar-button
      type="danger"
      text="立即购买"
      @click="SkuShow = true"
    />
  </van-action-bar>

  <!-- 拼团信息 -->
  <div class="teamwork">
    <img src="/assets/images/teamwork.jpg" alt="" />
  </div>
  <!-- 分享面板 -->
  <div class="share">
    <img src="/assets/images/share.png" alt="" />
  </div>
</template>
<script setup>
import { getCurrentInstance, onBeforeMount, ref } from "vue";
import VanSku from "vant-sku";
import "vant-sku/dist/index.css";

const { proxy } = getCurrentInstance();

//商品信息
let product = ref([]);
let comment = ref([]);

let TabActive = ref(0);
let rate = ref(4.5);

let SkuShow = ref(false);
let TipShow = ref(false);
let sku = ref({});
let properties = ref(null);
let goods = ref({});

//获取Sku元素节点
let SkuRef = ref({});
let teamid = ref(0)

//商品id
let proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0;

//拼团id
teamid.value = proxy.$cookies.get('teamid') ? proxy.$cookies.get('teamid') : ''

onBeforeMount(() => {
  info();
  if(teamid.value){
    SkuShow.value = true;
  }
});

var params = {
  proid,
};

if (proxy.$business.value.id) {
  params.busid = proxy.$business.value.id;
}
//获取商品信息
const info = async () => {
  var result = await proxy.$POST({
    url: "product/info",
    params,
  });

  if (result.code == 0) {
    proxy.$fail({
      message: result.msg,
      duration: 1000,
      onClse: () => proxy.$router.go(-1),
    });
    return;
  }

  const ProductData = result.data.product;
  const CommentData = result.data.comment;
  const SkuData = result.data.sku;
  const PropertiesData = result.data.properties;

  //星级，需要给数组参数
  CommentData.map((item) => (item.rate = parseInt(item.rate)));

  product.value = ProductData;
  comment.value = CommentData;
  goods.value = { picture: ProductData.thumbs_text };
  sku.value = SkuData;
  properties.value = Object.values(PropertiesData);

  return;
};

const collection = async () => {
  if (!proxy.$business.value.id) {
    proxy.$fail("请先登录");
    return false;
  }

  //已经登录
  var result = await proxy.$POST({
    url: "/product/collection",
    params: {
      busid: proxy.$business.value.id,
      collectid: proid,
    },
  });

  if (result.code == 0) {
    proxy.$fail(result.msg);
    return;
  } else if (result.code == 1) {
    product.value.collected = result.data == "add" ? true : false;
    return;
  }
};

// 添加购物车
const AddCart = async (SkuData) => {
  //判断是否有登录
  if (!proxy.$business.value.id) {
    proxy.$fail("请先登录");
    return false;
  }

  //判断是否有选择规格
  if (properties.value.length > 0 && !SkuData.selectedSkuComb) {
    proxy.$fail("请先选择规格");
    return false;
  }

  var relationids = [];

  if (SkuData.selectedSkuComb) {
    var SkuProps = SkuData.selectedSkuComb
      ? SkuData.selectedSkuComb.properties
      : null;
    for (var item of SkuProps) {
      let id = item.v[0] ? item.v[0]["id"] : 0;
      if (id) relationids.push(id);
    }
  }

  //组装数据
  var params = {
    busid: proxy.$business.value.id,
    proid: proid,
    nums: SkuData.selectedNum,
    relationids: relationids.join(","),
  };

  //发送请求
  var result = await proxy.$POST({
    url: "/cart/add",
    params,
  });

  //隐藏弹出框
  SkuShow.value = false;

  if (result.code == 0) {
    proxy.$fail(result.msg);
    return false;
  }

  proxy.$success(result.msg);
  //更新购物车数量
  product.value.cart = result.data;
};

//单独购买
const Buy = async (SkuData) => {
  console.log("单独购买");
  console.log(SkuData);
};

//参与拼团
const JoinTeam = async () =>{
  //判断是否有登录
  if (!proxy.$business.value.id) {
    proxy.$fail("请先登录");
    return false;
  }

  var SkuData = SkuRef.value.getSkuData()
  //判断是否有选择规格
  if (properties.value.length > 0 && !SkuData.selectedSkuComb) {
    proxy.$fail("请先选择规格");
    return false;
  }

  var relationids = [];
  if (SkuData.selectedSkuComb) {
    var SkuProps = SkuData.selectedSkuComb
      ? SkuData.selectedSkuComb.properties
      : null;
    for (var item of SkuProps) {
      let id = item.v[0] ? item.v[0]["id"] : 0;
      if (id) relationids.push(id);
    }
  }
  //商品规格存入cookie
  proxy.$cookies.set('relationids',relationids)

  if(!teamid.value){
    proxy.$router.push({path:'/team/index',query:{'proid':proid}})
  }else{
    let params = {
      'teamid':teamid.value,
      'proid':proid
    }
    //检测是否有对应拼团存在
    var result = await proxy.$POST({
      url:'/teambus/check',
      params
    })
    console.log(result)
    if(result.code == 0){
      proxy.$router.push({path:'/team/index',query:{'proid':proid}})
    }else{
      proxy.$router.push({path:'/team/confirm',query:{'proid':proid}})
    }
  }
  
  
}

//购物车
const ToCart = () => proxy.$router.push("/cart/index");
</script>